import { dataSource } from "../../db/typeorm";
import { Org } from "../../entity/org";
import { OrgTree } from "./type";
import { orgArrayToTree } from "./utils";

// 获取组织树
export async function orgTree({
  parent_id,
  user_id,
}: {
  parent_id?: number | string;
  user_id?: string | number;
}) {
  let querySql = dataSource.getRepository(Org).createQueryBuilder();
  let dats: Org[] = [];

  dats = await querySql.getMany();

  return orgArrayToTree(dats as unknown as OrgTree[]);
}

// 添加组织
export async function orgAdd(insertData: Org) {
  const response = await dataSource
    .createQueryBuilder()
    .insert()
    .into(Org)
    .values(insertData)
    .execute();
  return response;
}

// 查询单个组织详情
export async function orgFindOne(data: any) {
  return await dataSource.getRepository(Org).findOneBy(data);
}

// 修改组织
export async function orgUpdate(orgInfo: Org) {
  const result = await dataSource
    .createQueryBuilder()
    .insert()
    .update(Org)
    .set(orgInfo)
    .where("org_id = :id", { id: orgInfo.org_id })
    .execute();
  return result;
}

// 根据ids [] 删除组织
export async function orgDelByUserIds(ids: string[]) {
  await dataSource.getRepository(Org).delete(ids);
}
